package org.bleep.physics;

import org.bleep.util.Color;
import org.bleep.physics.Vector2D;
import org.bleep.util.Drawable;

import org.lwjgl.opengl.GL11;

import java.util.Random;

public class FastParticles implements Drawable
{
	private static int X_COORD = 0;
	private static int Y_COORD = 1;
	private static int X_VELOCITY = 2;
	private static int Y_VELOCITY = 3;
	private static int Y_ACCEL = 4;
	
	private static int size = 2;
	
	private boolean collide;
	private int ttl;
	private float threshold = 0.001f;
	private float elasticity = 0.2f;
	private float drag = 0.5f;
	
	private int numParticles;
	private Color color;
	private float[][] particles;
	private float[][] velocities;
	private float gravity;
	private float floor;
	
	public FastParticles(int numParticles, float minVelocity, float maxVelocity, Color color, float x, float y)
	{
		Random r = new Random();
		
		gravity = 0.01f;
		floor = 240f;
		collide = true;
		
		ttl = 300;
		
		this.numParticles = numParticles;
		this.color = color;
		particles = new float[numParticles][5];
		for (int i = 0; i < numParticles; i++)
		{
			double theta = r.nextDouble() * (2.0 * Math.PI);
			float magnitude = r.nextFloat() * (maxVelocity - minVelocity) + minVelocity;
			Vector2D v = Vector2D.withMagAndAngle(magnitude, theta);
			particles[i][X_COORD] = x;
			particles[i][Y_COORD] = y;
			particles[i][X_VELOCITY] = v.getX();
			particles[i][Y_VELOCITY] = v.getY();
			particles[i][Y_ACCEL] = gravity;
		}
	}
	
	public void update()
	{
		ttl--;
		for (int i = 0; i < numParticles; i++)
		{
			if (collide)
			{
				if (particles[i][Y_COORD] > floor)
				{
				
					float newXVelocity = particles[i][X_VELOCITY] * drag;
					particles[i][X_VELOCITY] = Math.abs(newXVelocity) < threshold ? 0f : newXVelocity;
			
					float newYVelocity = particles[i][Y_VELOCITY] *= elasticity * -1f;
					if (Math.abs(newYVelocity) < threshold)
					{
						particles[i][Y_VELOCITY] = 0f;
						particles[i][Y_ACCEL] = 0f;
					}
				}
			}
			particles[i][Y_VELOCITY] += particles[i][Y_ACCEL];
			particles[i][X_COORD] += particles[i][X_VELOCITY];
			particles[i][Y_COORD] += particles[i][Y_VELOCITY];
		}
	}
	
	public void draw()
	{
		GL11.glDisable(GL11.GL_TEXTURE_2D);
		color.glColor();
		GL11.glBegin(GL11.GL_POINTS);
		for (int i = 0; i < numParticles; i++)
		{
			int x = (int)(particles[i][X_COORD] + 0.5f);
			int y = (int)(particles[i][Y_COORD] + 0.5f);
			GL11.glVertex3i(x, y, 0);
			/*GL11.glVertex3i(x + size, y, 0);
			GL11.glVertex3i(x + size, y - size, 0);
			GL11.glVertex3i(x, y - size, 0);*/
		}
		GL11.glEnd();
		GL11.glEnable(GL11.GL_TEXTURE_2D);
	}
	
	public boolean isAlive()
	{
		return ttl > 0;
	}
}